package com.letfox.ad.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.letfox.ad.model.ADAppJson;

public class test {
	public static void main(String[] args) throws Exception {
		String request_json="{\"api_version\":\"3.0.0\",\"app\":{\"app_id\":\"235\",\"channel_id\":null,\"app_version\":\"2.2.1\",\"package_name\":\"sina.com\"},\"ad_place\":{\"place_id\":\"773\",\"width\":0,\"height\":0,\"render_type\":2,\"ad_count\":10},\"device\":{\"device_type\":4,\"os_type\":\"android\",\"os_version\":\"4.4.4\",\"vendor\":\"OPPO\",\"model\":\"OPPO R7\",\"android_id\":\"6abecb329c488c5a\",\"android_id_md5\":\"23c6f2df1e5b89e1076d97f5e165895e\",\"imei\":\"868698028568766\",\"imei_md5\":\"718aff214d4e7eeaccea2f2ea63ec46d\",\"w\":768,\"h\":1280,\"mac\":\"14:B4:84:5A:8C:2A\",\"idfa\":\"\",\"ua\":\"Mozilla/5.0 (Linux; Android 4.4.4;OPPO R7 Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Mobile Safari/537.36\",\"dpi\":3,\"meid\":null,\"language\":\"zh\",\"rp\":null,\"por\":0,\"isroot\":0,\"btmac\":\"02:00:00:00:8C:2A\",\"openudid\":\"773befa90654416e83db372a5fd213f2\",\"imsi\":\"460077112051046\",\"resolution\":\"1080*1920\",\"orientation\":0,\"referer\":\"www.gm825.com\",\"android_advertising_id\":\"1e19d1cb96a1460ba6a3de51c2707e1e\",\"idfv\":null,\"openudid\":null,\"battery\":75,\"country\":\"China\",\"iccid\":\"56d1cd3af42f450c9fe5e9464b4080ca\"},\"network\":{\"ip\":\"192.168.3.16\",\"connect_type\":2,\"carrier\":0},\"gps\":{\"coordinate_type\":1,\"lon\":116.41948166666667,\"lat\":40.06506,\"timestamp\":0,\"location_accuracy\":0.1,\"coord_time\":1447762376},\"sdkInfoVO\":null}";
		
		//压缩JSON数据
	    String byString=GzipUtil.compress(request_json,"UTF-8");
//		String params=GzipUtil.uncompress(byString);
//	    //访问的URL
		String url = "http://localhost:8080/live-ad-service/app/save";
		//设置参数
        Map<String, String> map=new HashMap<String, String>();
        map.put("params", byString);
        //访问连接
        String restu=doPost(url,map,"UTF-8");
		System.out.println(restu);
//		byte[] string=encrypt("1534407318".getBytes(),"1q2w3e4r5t6k7a");
//		System.out.println(string);
//		System.out.println(decrypt(string,"1q2w3e4r5t6k7a0000"));
		
	}
	public static String doPost(String url, Map<String,String> map, String charset){
	    CloseableHttpClient httpClient = null;
	    HttpPost httpPost = null;
	    String result = null;
	    try{
	        httpClient = HttpClients.createDefault();
	        httpPost = new HttpPost(url);
	        //设置参数
	        List<NameValuePair> list = new ArrayList<NameValuePair>();
	        Iterator iterator = map.entrySet().iterator();
	        while(iterator.hasNext()){	
	            Map.Entry<String,String> elem = (Map.Entry<String, String>) iterator.next();
	            list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
	        }
	        if(list.size() > 0){
	            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
	            httpPost.setEntity(entity);
	        }
	        HttpResponse response = httpClient.execute(httpPost);
	        if(response != null){
	            HttpEntity resEntity = response.getEntity();
	            if(resEntity != null){
	                result = EntityUtils.toString(resEntity,charset);
	            }
	        }
	    }catch(Exception ex){
	        ex.printStackTrace();
	    }
	    return result;
	}
	 public static byte[] encrypt(byte[] data, String sKey) {
	        try {
	            byte[] key = sKey.getBytes();
	            // 初始化向量
	            IvParameterSpec iv = new IvParameterSpec(key);
	            DESKeySpec desKey = new DESKeySpec(key);
	            // 创建一个密匙工厂，然后用它把DESKeySpec转换成securekey
	            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
	            SecretKey securekey = keyFactory.generateSecret(desKey);
	            // Cipher对象实际完成加密操作
	            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
	            // 用密匙初始化Cipher对象
	            cipher.init(Cipher.ENCRYPT_MODE, securekey, iv);
	            // 现在，获取数据并加密
	            // 正式执行加密操作
	            return cipher.doFinal(data);
	        } catch (Throwable e) {
	            e.printStackTrace();
	        }
	        return null;
	    }

	    /**
	     * 解密
	     * @param src
	     * @param sKey
	     * @return
	     * @throws Exception
	     */
	    public static byte[] decrypt(byte[] src, String sKey) throws Exception {
	        byte[] key = sKey.getBytes();
	        // 初始化向量
	        IvParameterSpec iv = new IvParameterSpec(key); 
	        // 创建一个DESKeySpec对象
	        DESKeySpec desKey = new DESKeySpec(key);
	        // 创建一个密匙工厂
	        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
	        // 将DESKeySpec对象转换成SecretKey对象
	        SecretKey securekey = keyFactory.generateSecret(desKey);
	        // Cipher对象实际完成解密操作
	        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
	        // 用密匙初始化Cipher对象
	        cipher.init(Cipher.DECRYPT_MODE, securekey, iv);
	        // 真正开始解密操作
	        return cipher.doFinal(src);
	    }

}
